<?php
namespace Catalog\Data;

use Catalog\Entity\Basket;
use Doctrine\ORM\Query\ResultSetMapping;

/**
 *
 * @author Paolo Bertuzzo
 *        
 */
class BasketDao extends AbstractDao
{

    /**
     * 
     * @param string $sessionId
     * @param integer $storeId
     */
    public function get($sessionId, $storeId)
    {
        $query = $this->entityManager->createQuery('select b from Catalog\Entity\Basket b where b.sessionId = ?1 and b.storeId = ?2');
        
        $query->setParameter(1, $sessionId);
        $query->setParameter(2, $storeId);

        return $query->getResult();
    }
    
    /**
     * 
     * @param string $sessionId
     * @param int $storeId
     * @param int $itemsCount
     * @param number $total
     * @param string $currency
     */
    public function insert($sessionId, $storeId, $itemsCount, $total, $currency)
    {
    	$basket = new Basket();
    	
    	$basket->setSessionId($sessionId);
    	$basket->setStoreId($storeId);
    	$basket->setCurrency($currency);
    	$basket->setTotal($total);
    	$basket->setItemsCount($itemsCount);
    	
    	$this->entityManager->persist($basket);
    	$this->entityManager->flush();
    	
    	return $basket;
    }
    
    /**
     * 
     * @param int $basketId
     * @param int $itemsCount
     * @param number $total
     * @return unknown
     */
    public function update($basketId, $itemsCount, $total)
    {
    	$basket = $this->entityManager->find('Catalog\Entity\Basket', $basketId);
    	
    	if (is_null($basket)) {
    		$this->logger->info(sprintf('Basket not found for id %d', $basketId));
    		
    		return;
    	}
    	 
    	$basket->setItemsCount($itemsCount);
    	$basket->setTotal($total);
    	
    	$this->entityManager->flush();
    	
    	return $basket;
    }
    
    /**
     * 
     * @param string $sessionId
     */
    public function getShippingTax($sessionId)
    {
        $resultSetMapping = new ResultSetMapping();

        $resultSetMapping->addScalarResult('shipping_taxes', 'result');
        
    	$query = $this->entityManager->createNativeQuery('SELECT get_shipping_taxes(?) as shipping_taxes', $resultSetMapping);
        
        $query->setParameter(1, $sessionId);
        
    	return $query->getResult()[0]['result'];
    }
    
}

?>